package cn.wei.reallyEnjoy.app;



import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import cn.wei.reallyEnjoy.R;
import cn.wei.reallyEnjoy.home.adapter.CommentAdapter;
import cn.wei.reallyEnjoy.home.bean.CommentBean;
import cn.wei.reallyEnjoy.home.bean.CommentListBean;
import cn.wei.reallyEnjoy.home.bean.RecordBean;

import cn.wei.reallyEnjoy.utils.Constants;
import cn.wei.reallyEnjoy.utils.KeyboardUtils;
import cn.wei.reallyEnjoy.utils.Utility;
import okhttp3.Call;


public class RecordDetailActivity extends Activity implements View.OnClickListener {
    private ImageButton ibRecordDetailBack;
    private ImageView ivRecordDetailImage;
    private ImageView iv_detail_user_headimg;
    private TextView tvRecordDetailTitle;
    private TextView iv_detail_user_name;
    private TextView tv_detail_favorites;
    private TextView tv_detail_time;
    private TextView tvRecordDetailContent;
    private ListView lv_comments;
    private LinearLayout llRecordRoot;
    private EditText commentEdit;
    private TextView tvRecordDetailCollection;
    private RecordBean recordBean;
    private Button btn_commit_comment;
    private String uid;
    private Boolean isFavorites;


    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2021-11-27 19:02:53 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {

        ibRecordDetailBack = (ImageButton)findViewById( R.id.ib_record_detail_back );
        ivRecordDetailImage = (ImageView)findViewById( R.id.iv_record_detail_image );
        iv_detail_user_headimg = (ImageView)findViewById( R.id.iv_detail_user_headimg );
        tvRecordDetailTitle = (TextView)findViewById( R.id.tv_record_detail_title );
        tvRecordDetailContent = (TextView)findViewById( R.id.tv_record_detail_content );
        iv_detail_user_name = (TextView)findViewById( R.id.iv_detail_user_name );
        tv_detail_favorites = (TextView)findViewById( R.id.tv_detail_favorites );
        tv_detail_time = (TextView)findViewById( R.id.tv_detail_time );
        lv_comments = (ListView) findViewById( R.id.lv_comments );
        llRecordRoot = (LinearLayout)findViewById( R.id.ll_record_root );
        commentEdit = (EditText)findViewById( R.id.comment_edit );
        tvRecordDetailCollection = (TextView)findViewById( R.id.tv_record_detail_collection );
        btn_commit_comment = (Button)findViewById( R.id.btn_commit_comment );


        //设置监听
        ibRecordDetailBack.setOnClickListener( this );
        commentEdit.setOnClickListener( this );
        tvRecordDetailCollection.setOnClickListener( this );
        btn_commit_comment.setOnClickListener( this );
    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2021-11-27 19:02:53 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == ibRecordDetailBack ) {
            // Handle clicks for ibRecordDetailBack
            // 退出
            finish();
        }else if (v==commentEdit){
            Toast.makeText(this, "评论", Toast.LENGTH_SHORT).show();
        }
        else if(v==tvRecordDetailCollection){
            userCollectionOrCancel();

        }
        else if(v==btn_commit_comment){
            String comment = commentEdit.getText().toString().trim();
            if (TextUtils.isEmpty(comment)){
                Toast.makeText(this,"评论内容不能为空：",Toast.LENGTH_SHORT).show();
                return;
            }else{
                //获取用户id


                if (TextUtils.isEmpty(uid)){
                    Toast.makeText(RecordDetailActivity.this, "未登录，请先登录", Toast.LENGTH_LONG).show();
                    return;
                }
                String url = Constants.USER_COMMENT_URL;
                OkHttpUtils.post()
                        .url(url)
                        .addParams("userId",uid)
                        .addParams("diaryId",recordBean.getRecord_id())
                        .addParams("body",comment)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Toast.makeText(RecordDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                Toast.makeText(RecordDetailActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                                commentEdit.setText("");
                                commentEdit.clearFocus();//取消焦点
                                // 关闭输入法
                                KeyboardUtils.hideKeyboard(RecordDetailActivity.this);

                                //刷新评论数据
                                setCommentData(recordBean.getRecord_id());

                            }
                        });
            }

        }

    }

    /**
     * 用户收藏或取消收藏
     */
    private void userCollectionOrCancel() {
        String url = Constants.USER_COLLECTION+recordBean.getRecord_id()+"/"+uid;
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(RecordDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }

                   @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObject = JSON.parseObject(response);
                        String code = String.valueOf(jsonObject.get("code"));
                        if (TextUtils.equals(code,"0")){
                            Toast.makeText(RecordDetailActivity.this, "操作成功", Toast.LENGTH_SHORT).show();

                            isCollection(recordBean.getRecord_id(),uid);
                            int num = Integer.parseInt(tv_detail_favorites.getText().toString());
                            if (isFavorites){
                               //收藏后取消收藏
                                tv_detail_favorites.setText(""+(num-1));
                            }else{
                                //收藏
                                tv_detail_favorites.setText(""+(num+1));
                            }

                        }
                    }
                });
    }

    /**
     *
     * @param record_id：日记id
     * @param uid：用户id
     */
    private void isCollection(String record_id, String uid) {
        String url = Constants.USER_IS_COLLECTION+record_id+"/"+uid;
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(RecordDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObject = JSON.parseObject(response);
                        String res = String.valueOf(jsonObject.get("data"));
                        if (TextUtils.equals(res,"true")){
                            isFavorites = true;
                            Drawable drawable = getResources().getDrawable(
                                    R.drawable.iscollecting);
                            tvRecordDetailCollection.setCompoundDrawablesWithIntrinsicBounds(null,drawable,null,null);
                            tv_detail_favorites.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);

                        }else{
                            isFavorites=false;
                            Drawable drawable = getResources().getDrawable(R.drawable.aixin);
                            tvRecordDetailCollection.setCompoundDrawablesWithIntrinsicBounds(null,drawable,null,null);
                            tv_detail_favorites.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);


                        }
                    }
                });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_detail);
        findViews();
        readUser();


        //接收数据
        recordBean = (RecordBean) getIntent().getSerializableExtra("recordBean");
        if (recordBean!=null){
            SetDataForView(recordBean);
        }
    }

    private void readUser() {
        SharedPreferences sp = this.getSharedPreferences("user", MODE_PRIVATE);
        String userId = sp.getString("id", "");
        uid= userId;
    }

    /**
     * 设置数据
     * @param recordBean
     */
    private void SetDataForView(RecordBean recordBean) {
        Glide.with(this).load(Constants.IMG_URL+recordBean.getImg()).into(ivRecordDetailImage);
        Glide.with(this).load(Constants.IMG_URL+recordBean.getUheadImg()).into(iv_detail_user_headimg);

        iv_detail_user_name.setText(recordBean.getUname());
        tv_detail_favorites.setText(recordBean.getPrefer());
        tv_detail_time.setText(recordBean.getCreateTime());
        tvRecordDetailTitle.setText(recordBean.getTitle());
        tvRecordDetailContent.setText(recordBean.getContent());
        //判断用户是否收藏
        isCollection(recordBean.getRecord_id(),uid);



        //设置日志评论数据
         setCommentData(recordBean.getRecord_id());

    }

    private void setCommentData(String record_id) {
        String url = Constants.DIARY_COMMENT_URL;
        OkHttpUtils
                .get()
                .url(url+record_id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(RecordDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //json解析
                        JSONObject jsonObject = JSON.parseObject(response);
                        String code = (String) jsonObject.get("code");
                        if (!TextUtils.equals(code,"0")){
                            String message = (String) jsonObject.get("msg");
                            Toast.makeText(RecordDetailActivity.this,message, Toast.LENGTH_SHORT).show();
                        }else{
                            //解析json数据，生成评论列表对象
                            //获取data节点
                            String data =String.valueOf(jsonObject.get("data"));
                            CommentListBean commentListBean = JSON.parseObject(data, CommentListBean.class);
                            for (CommentBean commentBean : commentListBean.getDiaryCommentList()) {
                                System.out.println(commentBean.toString());
                            }


                            //设置评论
                            lv_comments.setAdapter( new CommentAdapter(RecordDetailActivity.this,commentListBean.getDiaryCommentList()));
                            //layout中ScrollView 只计算listView第一个item的高度，
                            // 因而只会显示一条数据的高度，无法滑动，
                            // 使用该工具类重新计算高度。
                            Utility.setListViewHeightBasedOnChildren(lv_comments);

                        }
                    }
                });
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}